import { _decorator, assetManager, AudioClip, Component, director, Node } from 'cc';
import { L } from './L';
const { ccclass, property } = _decorator;

export class Utils {
    /**
     * 在当前场景根据path查找节点(Node), 并在这个节点上找到对应的组件(Component)
     * @param path 
     * @param type 
     * @returns 
     */
    public static findComponent<T extends Component>(path: string, type: new () => T): T | null {
        const scene = director.getScene();
        if (!scene) {
            L.warn('当前没有激活的场景');
            return null;
        }

        const node = scene.getChildByPath(path);
        if (!node?.isValid) {
            L.warn(`找不到path: ${path} 的节点`);
            return null;
        }

        const component = node.getComponent(type);
        if (!component?.isValid) {
            L.warn(`找不到path: ${path} 下的 ${type.name} Component`);
            return null;
        }

        return component;
    }

    public static pad(num: number, length: number): string {
        let str = num.toString();
        while (str.length < length) {
            str = '0' + str;
        }
        return str;
    }
}

